//
//  JKMainViewController.swift
//  新浪微博
//
//  Created by Jack.Lin on 16/6/29.
//  Copyright © 2016年 Jack.Lin. All rights reserved.
//

import UIKit
import SVProgressHUD

class JKMainViewController: UITabBarController {

    // 定时器
    private var timer: Timer?
    
    override func viewDidLoad() {
        super.viewDidLoad()

        
        
        setupChildControllers()
        setupComposeButton()

         setupTimer()
        
        setupNewfeatureView()
        
        delegate = self
        
        NotificationCenter.default.addObserver(self, selector: #selector(userLogin), name: NSNotification.Name(rawValue: JKUserShouldLoginNotification), object: nil)
    }
    
    
    deinit {
        timer?.invalidate()
        
        NotificationCenter.default.removeObserver(self)

    }
    
    
    /** portrait: 竖屏 , 肖像
        landscape: 横屏 , 风景画
        使用代码控制设备的方向,可以单独控制不同界面的横屏
        如果这里设置设备的方向,当前控制器跟子控制器都会遵守
        视频播放使用 modal 展现的
        记得测试
     */
    
    override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
        return .portrait
//        return .landscape
    }
   
    
    @objc private func userLogin(n: Notification) {
       print("用户登录通知 \(n)")
        
//        let nav = UINavigationController(rootViewController: JKOAuthViewController())
        
        var when = DispatchTime.now()
        
//        present(nav, animated: true, completion: nil)
      
        if n.object != nil {
            // 设置指示器渐变样式
            SVProgressHUD.setDefaultMaskType(.gradient)
            
            SVProgressHUD.showInfo(withStatus: "用户登录已经超时，需要重新登录")
            
            // 修改延迟时间
            when = DispatchTime.now() + 2

        }
        
        DispatchQueue.main.after(when: when) {
            SVProgressHUD.setDefaultMaskType(.clear)
            
            // 展现登录控制器 - 通常会和 UINavigationController 连用，方便返回
            let nav = UINavigationController(rootViewController: JKOAuthViewController())
            
            self.present(nav, animated: true, completion: nil)
        }

    }
    

    // private 能够保证方法私有,尽在当前对象访问
    // @objc 允许这个函数在'运行时'通过 OC 的消息机制被调用
    @objc private func composeStatus() {
         print("撰写微博")
        
        let v = JKComposeTypeView.composeTypeView()
        
//        let nav = UINavigationController(rootViewController: vc)
//        // 相当于 Modal
//        present(nav, animated: true, completion: nil)

        // 2> 显示视图 - 注意闭包的循环引用！
        v.show { [weak v] (clsName) in
            print(clsName)
            
            // 展现撰写微博控制器
            guard let clsName = clsName,
                let cls = NSClassFromString(Bundle.main.namespace + "." + clsName) as? UIViewController.Type
                else {
                    v?.removeFromSuperview()
                    return
            }
            
            let vc = cls.init()
            let nav = UINavigationController(rootViewController: vc)
            
            self.present(nav, animated: true) {
                v?.removeFromSuperview()
            }
        }
    }
    
    
    // MARK - 私有控件
    private lazy var composeButton: UIButton = UIButton.cz_imageButton(
        "tabbar_compose_icon_add",
        backgroundImageName: "tabbar_compose_button")
    
}

// MARK - 时钟相关方法

extension JKMainViewController {
   
    private func setupTimer() {
    
        // 时间间隔建议长一些
        timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true)
    }
    
    @objc private func updateTimer() {
     
        JKNetworkManager.shared.unreadCount { (count) in
            print("检测到 \(count) 条新微博")
            
            if !JKNetworkManager.shared.userLogon {
               return
            }
            
            self.tabBar.items?[0].badgeValue = count > 0 ? "\(count)" : nil
        
            // 设置 App 的 badgeNumber, 从 iOS 8.0 之后, 要用户授权之后才能够显示
            UIApplication.shared().applicationIconBadgeNumber = count
        }
    }
    
}



// MARK - UITabBarControllerDelegate

extension JKMainViewController: UITabBarControllerDelegate {

       func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
//        print("将要切换到 \(viewController)")
        let idx = (childViewControllers as NSArray).index(of: viewController)
        
        if selectedIndex == 0 && idx == selectedIndex {
            
            let nav = childViewControllers[0] as! UINavigationController
            let vc = nav.childViewControllers[0] as! JKHomeViewController
            
            vc.tableView?.setContentOffset(CGPoint(x: 0, y: -64), animated: true)
            
            DispatchQueue.main.after(when: DispatchTime.now() + 1, execute: { 
                vc.loadData()
            })

            // 取消提示按钮
            vc.tabBarItem.badgeValue = nil
            UIApplication.shared().applicationIconBadgeNumber = 0
        }
        
        return !viewController.isMember(of: UIViewController.self)
    }
}


// MARK - 设置界面

extension JKMainViewController {
    
    // 设置撰写按钮 
    private func setupComposeButton() {
    
        tabBar.addSubview(composeButton)
        
        let count = CGFloat(childViewControllers.count)
        
        let w = tabBar.bounds.width / count
        
        composeButton.frame = tabBar.bounds.insetBy(dx: 2 * w, dy: 0)
        print("撰写按钮宽度 \(composeButton.bounds.width)")
        
        composeButton.addTarget(self, action: #selector(composeStatus), for: .touchUpInside)

    }
    
    
        private func setupChildControllers() {
        
            let docDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
            let jsonPath = (docDir as NSString).appendingPathComponent("main.json")
            
            var data = NSData(contentsOfFile: jsonPath)
            
            if data == nil {
                let path = Bundle.main.pathForResource("main.json", ofType: nil)
                
                data = NSData(contentsOfFile: path!)
            }
            
            guard let array = try? JSONSerialization.jsonObject(with: data! as Data, options: []) as? [[String: AnyObject]]
                else {
                     return
            }
            
            
            var arrayM = [UIViewController]()
            for dict in array! {
                arrayM.append(controller(dict: dict))
            }
            viewControllers = arrayM
            
        }
    }
    
    private func controller(dict: [String: AnyObject]) -> UIViewController {
    
        guard let clsName = dict["clsName"] as? String,
            title = dict["title"] as? String,
            imageName = dict["imageName"] as? String,
            
            cls = NSClassFromString(Bundle.main.namespace + "." + clsName) as? JKBaseViewController.Type,
            visitorDict = dict["visitorInfo"] as? [String: String]
        else {
            return UIViewController()
        }
        
        let vc = cls.init()
        
        vc.title = title
        vc.visitorInfoDictionary = visitorDict
        vc.tabBarItem.image = UIImage(named: "tabbar_" + imageName)
        vc.tabBarItem.selectedImage = UIImage(named: "tabbar_" + imageName + "_selected")?.withRenderingMode(.alwaysOriginal)
        // 系统默认字体大小是 12
        vc.tabBarItem.setTitleTextAttributes([NSFontAttributeName: UIFont.systemFont(ofSize: 12)], for: UIControlState(rawValue: 0))
        vc.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.orange()], for: UIControlState(rawValue: 0))
        
        
        // 实例化导航控制器的时候, 会调用 push 方法将 rootVC 压栈
        let nav = JKNavigationController(rootViewController: vc)
        
        return nav
    
    }

// MARK: - 新特性视图处理
extension JKMainViewController {
    
    private func setupNewfeatureView() {
        
        if !JKNetworkManager.shared.userLogon {
           return
        }
        
        let v = isNewVersion ? JKNewFeatureView.newFeatureView() : JKWelcomeView.welcomeView()
        
        v.frame = view.bounds
        
        view.addSubview(v)
        
    }
    
    private var isNewVersion: Bool {
        
        // 1. 取当前的版本号 
        let currentVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? ""
        print("当前版本" + currentVersion)
        
        // 2. 取保存在 `Document(iTunes备份)[最理想保存在用户偏好]` 目录中的之前的版本号 
        let path: String = ("Version" as NSString).cz_appendDocumentDir()
        let sandboxVersion = (try? String(contentsOfFile: path)) ?? ""
        print("沙盒版本" + sandboxVersion)
        
        // 3. 将当前版本号保存在沙盒
        _ = try? currentVersion.write(toFile: path, atomically: true, encoding: .utf8)
        // 4. 返回两个版本号 是否一致

        // 出现新特性
//        return currentVersion == sandboxVersion
//         不会出现新特性
         return currentVersion != sandboxVersion
    }
    
}

